package com.central.apps.controller;


import com.central.apps.dao.DkPrintTerminalDao;
import com.central.apps.entity.DkPrintTerminal;
import com.central.apps.util.HttpUtil;
import com.central.apps.util.QRCodeFileUtil;
import com.central.common.web.Result;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.UUID;

/**
 * (DkPrintLog)表控制层
 *
 * @author makejava
 * @since 2022-05-19 17:25:44
 */
@Log4j2
@RestController
@RequestMapping("/dkPrintLog")
public class DkPrintLogController {

    /**
     * 服务对象

    @Autowired
    private DkPrintLogService dkPrintLogService;*/
    @Autowired
    private DkPrintTerminalDao dkPrintTerminalDao;


    /**//**
     * 通过主键查询单条数据
     *
     * @param dkPrintLog
     * @return 单条数据
     *//*
    @GetMapping("/queryPrintLog")
    public Result queryPrintLogList(DkPrintLog dkPrintLog) {
        PageInfo<DkPrintLog> dkPrintLogs = dkPrintLogService.queryPrintLogList(dkPrintLog);
        return Result.succeed(dkPrintLogs,"操作成功");
    }

    *//**
     * 新增数据
     *
     * @param dkPrintLog 实体
     * @return 新增结果
     *//*
    @PostMapping("/save")
    public ResponseEntity<DkPrintLog> add(@RequestBody DkPrintLog dkPrintLog) {
        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
        dkPrintLog.setCreateuser(loginAppUser.getId().toString());
        dkPrintLog.setCreateTime(new Date());
        return ResponseEntity.ok(this.dkPrintLogService.insert(dkPrintLog));
    }

    *//**
     * 编辑数据
     *
     * @param dkPrintLog 实体
     * @return 编辑结果
     *//*
    @PostMapping("/update")
    public ResponseEntity<DkPrintLog> edit(DkPrintLog dkPrintLog) {
        return ResponseEntity.ok(this.dkPrintLogService.update(dkPrintLog));
    }

    *//**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     *//*
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.dkPrintLogService.deleteById(id));
    }*/

    /**
     * 标签打印
     *
     * @param
     * @return
     */
    @PostMapping("/applabelPrint")
    public Result queryPrintLogList(@RequestBody Map<String, Object> params) throws Exception {
        String id = MapUtils.getString(params, "id", "1c9c555d24330e298a8d7681e3d4cc81");
        List<String> file = (List<String>) params.get("file");
        DkPrintTerminal dkPrintTerminal = new DkPrintTerminal();
        dkPrintTerminal.setId(id);
        DkPrintTerminal dkPrintTerminal1 = dkPrintTerminalDao.queryById(dkPrintTerminal);
        Double width = dkPrintTerminal1.getWidth();
        Double height = dkPrintTerminal1.getLength();
        String[] ips = dkPrintTerminal1.getIp().split(":");
        if(ips.length != 2){
            return Result.failed("打印终端连接信息不正确");
        }
        String ip = ips[0];
        String port = ips[1];
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String path = "/home/eam/" + uuid;
        //String path = "D:/43abbeae53784a509d7d67a119f98569";
//        List<String> fileNames = new ArrayList<>();
        List<String> fileNames = QRCodeFileUtil.GenerateImage(file, path);
        Object o = "";
        for(String filepath : fileNames){
            StringJoiner sj = new StringJoiner(",","[","]");
            sj.add("{\"PTK_Connect_Timer\":\"" + ip + "," + port + ",5\"}");//ip,端口,超时时间
            sj.add("{\"PTK_ClearBuffer\":\"\"}");//清除打印机中的缓冲内容 空即可
            sj.add("{\"PTK_SetDarkness\":10}");//标签打印黑度。取值：0 – 20 的正整数，值越大打印黑度越深。
            sj.add("{\"PTK_SetPrintSpeed\":4}");//设置当前标签打印速度
            sj.add("{\"PTK_SetDirection\":\"T\"}");// 方向。T -> 从顶部开始打印 B -> 从底部开始打印
            sj.add("{\"PTK_SetLabelHeight\":\"" + height + ",0,0,false\"}");//这个是整个的宽度出纸长度1305正好 设置当前标签高度、定位间隙\黑标\穿孔的高度、定位偏移
            sj.add("{\"PTK_SetLabelWidth\":" + width + "}");//宽度是从正面看 右边开始计算的800有点靠右标签的宽度，以点(dots)为单位。取值：0 – 65535 的正整数
            sj.add("{\"PTK_AnyGraphicsPrint\":\"20,0,picture," + filepath + ",0," + width + "," + height + ",0\"}");//x,y,pcxname,filePath,ratio,width,height,iDire
            sj.add("{\"PTK_PrintLabel\":\"1,1\"}");//命令打印机开始打印标签内容
            sj.add("{\"PTK_CloseUSBPort\":\"\"}");//断开与打印机的网络连接 空即可

            String encodedUrl = URLEncoder.encode(sj.toString(), "UTF-8");

            log.info(sj.toString());
            o = HttpUtil.sendPost("http://127.0.0.1:888/postek/print", "reqParam=1&printparams=" + encodedUrl);
            log.info("调用标签打印机以后的返回结果" + o);
        }
        //删除临时文件夹
        //先循环删除图片
//        for(String filepath : files){
//            File file = new File(filepath);
//            boolean deleted = file.delete();
//            System.out.println(deleted);
//        }
        //再删除路径
//        File file = new File(path);
//        boolean deleted = file.delete();
//        System.out.println(deleted);

        return Result.succeed("操作成功");
    }

    /**
     * 标签打印
     *
     * @param
     * @return
     */
    @PostMapping("/labelPrint")
    public Result queryPrintLogList(MultipartFile[] fileList,
                                    @RequestParam(value="id",defaultValue = "1c9c555d24330e298a8d7681e3d4cc81") String id) throws Exception {
        DkPrintTerminal dkPrintTerminal = new DkPrintTerminal();
        dkPrintTerminal.setId(id);
        DkPrintTerminal dkPrintTerminal1 = dkPrintTerminalDao.queryById(dkPrintTerminal);
        Double width = dkPrintTerminal1.getWidth();
        Double height = dkPrintTerminal1.getLength();
        String[] ips = dkPrintTerminal1.getIp().split(":");
        if(ips.length != 2){
            return Result.failed("打印终端连接信息不正确");
        }
        String ip = ips[0];
        String port = ips[1];
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String path = "/home/eam/" + uuid;
        //String path = "D:/43abbeae53784a509d7d67a119f98569";
        //创建临时文件
        List<String> files = QRCodeFileUtil.createFile(fileList, path);
        Object o = "";
        for(String filepath : files){
            StringJoiner sj = new StringJoiner(",","[","]");
            sj.add("{\"PTK_Connect_Timer\":\"" + ip + "," + port + ",5\"}");//ip,端口,超时时间
            sj.add("{\"PTK_ClearBuffer\":\"\"}");//清除打印机中的缓冲内容 空即可
            sj.add("{\"PTK_SetDarkness\":10}");//标签打印黑度。取值：0 – 20 的正整数，值越大打印黑度越深。
            sj.add("{\"PTK_SetPrintSpeed\":4}");//设置当前标签打印速度
            sj.add("{\"PTK_SetDirection\":\"T\"}");// 方向。T -> 从顶部开始打印 B -> 从底部开始打印
            sj.add("{\"PTK_SetLabelHeight\":\"" + height + ",0,0,false\"}");//这个是整个的宽度出纸长度1305正好 设置当前标签高度、定位间隙\黑标\穿孔的高度、定位偏移
            sj.add("{\"PTK_SetLabelWidth\":" + width + "}");//宽度是从正面看 右边开始计算的800有点靠右标签的宽度，以点(dots)为单位。取值：0 – 65535 的正整数
            sj.add("{\"PTK_AnyGraphicsPrint\":\"20,0,picture," + filepath + ",0," + width + "," + height + ",0\"}");//x,y,pcxname,filePath,ratio,width,height,iDire
            sj.add("{\"PTK_PrintLabel\":\"1,1\"}");//命令打印机开始打印标签内容
            sj.add("{\"PTK_CloseUSBPort\":\"\"}");//断开与打印机的网络连接 空即可

            String encodedUrl = URLEncoder.encode(sj.toString(), "UTF-8");

            log.info(sj.toString());
            o = HttpUtil.sendPost("http://127.0.0.1:888/postek/print", "reqParam=1&printparams=" + encodedUrl);
            log.info("调用标签打印机以后的返回结果" + o);
        }
        //删除临时文件夹
        //先循环删除图片
//        for(String filepath : files){
//            File file = new File(filepath);
//            boolean deleted = file.delete();
//            System.out.println(deleted);
//        }
        //再删除路径
//        File file = new File(path);
//        boolean deleted = file.delete();
//        System.out.println(deleted);

        return Result.succeed("操作成功");
    }



    /**
     * 标签打印
     *
     * @param
     * @return
     */
    @GetMapping("/labelPrintFromUSB")
    public Result labelPrintFromUSB(MultipartFile[] fileList) throws Exception {

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String path = "/home/eam/" + uuid;
//        String path = "D:/43abbeae53784a509d7d67a119f98569";
        //创建临时文件
        List<String> files = QRCodeFileUtil.createFile(fileList, path);

        for(String filepath : files){
            StringJoiner sj = new StringJoiner(",","[","]");
            sj.add("{\"PTK_OpenUSBPort\":\"255\"}");//ip,端口,超时时间
            sj.add("{\"PTK_ClearBuffer\":\"\"}");//清除打印机中的缓冲内容 空即可
            sj.add("{\"PTK_SetDarkness\":10}");//标签打印黑度。取值：0 – 20 的正整数，值越大打印黑度越深。
            sj.add("{\"PTK_SetPrintSpeed\":4}");//设置当前标签打印速度
            sj.add("{\"PTK_SetDirection\":\"T\"}");// 方向。T -> 从顶部开始打印 B -> 从底部开始打印
            sj.add("{\"PTK_SetLabelHeight\":\"850,24,0,false\"}");//这个是整个的宽度出纸长度1305正好 设置当前标签高度、定位间隙\黑标\穿孔的高度、定位偏移
            sj.add("{\"PTK_SetLabelWidth\":790}");//800有点靠右标签的宽度，以点(dots)为单位。取值：0 – 65535 的正整数
            sj.add("{\"PTK_AnyGraphicsPrint\":\"20,50,picture," + filepath + ",0,0,0,0\"}");//x,y,pcxname,filePath,ratio,width,height,iDire
            sj.add("{\"PTK_PrintLabel\":\"1,1\"}");//命令打印机开始打印标签内容
            sj.add("{\"PTK_CloseUSBPort\":\"\"}");//断开与打印机的网络连接 空即可

            String encodedUrl = URLEncoder.encode(sj.toString(), "UTF-8");

            log.info(sj.toString());
            Object o = HttpUtil.sendPost("http://127.0.0.1:888/postek/print", "reqParam=1&printparams=" + encodedUrl);
            log.info("调用标签打印机以后的返回结果" + o);
        }

        //删除临时文件夹
        //先循环删除图片
        for(String filepath : files){
            File file = new File(filepath);
            boolean deleted = file.delete();
            System.out.println(deleted);
        }
        //再删除路径
        File file = new File(path);
        boolean deleted = file.delete();
        System.out.println(deleted);

        return Result.succeed("操作成功");
    }

    /**
     * 标签打印
     *
     * @param
     * @return
     */
    @GetMapping("/status")
    public Result status() throws IOException {

        StringJoiner sj = new StringJoiner(",","[","]");
        sj.add("{\"PTK_OpenUSBPort\":\"1\"}");
        sj.add("{\"PTK_ErrorReport_USBInterrupt\":\"打印机状态:\"}");
        sj.add("{\"PTK_CloseUSBPort\":\"\"}");


        String encodedUrl = URLEncoder.encode(sj.toString(), "UTF-8");

        log.info(sj.toString());
        Object o = HttpUtil.sendPost("http://127.0.0.1:888/postek/print", "reqParam=1&printparams=" + encodedUrl);
        log.info("调用标签打印机以后的返回结果" + o);

        return Result.succeed(o.toString());
    }

}

